import json
import urllib.request

import urllib.request
import urllib.parse
import http.cookiejar as cookiejar

import sys
import getopt


# 保存cookie
jar = cookiejar.CookieJar()
handler=urllib.request.HTTPCookieProcessor(jar)
opener = urllib.request.build_opener(handler)
urllib.request.install_opener(opener)
    
# 获得zenao 
def GetZentaoSid(zentao_ref_url):
    zentao_url = str(zentao_ref_url + "api-getsessionid.json")
    post_data = {}
    post_data_json = urllib.parse.urlencode(post_data).encode(encoding='UTF8')
    header_dict = {}

    req = urllib.request.Request(method="POST", url=zentao_url, data=post_data_json, headers=header_dict)
    r = urllib.request.urlopen(zentao_url, post_data_json)
    d = json.loads(r.read())
    sid = json.loads(d['data'])
    #print(sid['sessionID'])
    return sid['sessionID']

# 用户登入
def UserLogin(zentao_ref_url, sid):
    zentao_url = zentao_ref_url + "/user-login.json"
    post_data = {}
    post_data['account'] = "liangyt"
    post_data['password'] = "Lyt123"
    post_data_json = urllib.parse.urlencode(post_data).encode(encoding='UTF8')
    header_dict = {}
    header_dict['zentaosid'] = sid

    req = urllib.request.Request(method="POST", url=zentao_url, data=post_data_json, headers=header_dict)
    r = urllib.request.urlopen(zentao_url, post_data_json)
    #print(r.read())

# 创建版本
def CreateVersion(zentao_ref_url, sid, post_data):
    zentao_url = zentao_ref_url + "/build-create-"+ str(post_data['project'])+".json"
    # zentao_url = zentao_ref_url + "/build-create-10"+".json"
    post_data_json = urllib.parse.urlencode(post_data).encode(encoding='UTF8')

    header_dict = {}
    req = urllib.request.Request(method="POST", url=zentao_url, data=post_data_json, headers=header_dict)
    r = urllib.request.urlopen(zentao_url, post_data_json)
    d = json.loads(r.read())
    print(d['result'], d['message'])

def usage():
    print ("""
    -h --help     [opt]使用帮助
    -z --zentao   [req]禅道路径,text eg:http://zt.com/zentao/
    -t --product  [req]产品,int
    -b --branch   [opt]平台/分支,int
    -j --project  [req]所属项目,int
    -n --name     [req]名称编号,char[150]
    -p --scmPath  [opt]源代码地址,char[255]
    -f --filePath [opt]下载地址,char[255]
    -d --date     [opt]打包日期,eg:2019-09-25
    -g --bugs     [opt]解决的Bug,text
    -u --builder  [opt]构建者,char[30]
    -s --desc     [opt]描述,text
    -l --deleted  [opt]已删除,enum('0','1')
    """)

global opts, args

def main(argv):
    try:
        opts,args = getopt.getopt(sys.argv[1:], 'hz:i:t:b:j:n:p:f:d:g:u:s:l:', ['help','zentao=','id=', 'product=', 'branch=', 'project=', 'name=', 'scmPath=', 'filePath=', 'date=', 'bugs=', 'builder=', 'desc=', 'deleted='])
    except getopt.GetoptError:
        print("opt_error")
        sys.exit()
        
    zentao_ref_url = ""
    post_data = {}
    for opt, arg in opts:
        if opt in ['-h', '--help']:
            usage()
            sys.exit()
        elif opt in ['-z', '--zentao']:
            zentao_ref_url = arg
        elif opt in ['-i', '--id']:
            post_data['id'] = arg
        elif opt in ['-t', '--product']:
            post_data['product'] = "3"
        elif opt in ['-b', '--branch']:
            post_data['branch'] = arg
        elif opt in ['-j', '--project']:
            post_data['project'] = arg
        elif opt in ['-n', 'name']:
            post_data['name'] = arg
        elif opt in ['-p', '--scmPath']:
            post_data['scmPath'] = arg
        elif opt in ['-f', '--filePath']:
            post_data['filePath'] = arg
        elif opt in ['-d', '--date']:
            post_data['date'] = arg
        elif opt in ['-g', '--bugs']:
            post_data['bugs'] = arg
        elif opt in ['-u', '--builder']:
            post_data['builder'] = arg
        elif opt in ['-s', '--desc']:
            post_data['desc'] = arg
        elif opt in ['-l', '--deleted']:
            post_data['deleted'] = arg
        else:
            print("Error: invalid parameters")
            usage()
            sys.exit()

    if zentao_ref_url=="":
        print("invalid zentao url.")
        usage()
        sys.exit()
    
        
    sid = GetZentaoSid(zentao_ref_url)
    UserLogin(zentao_ref_url, sid)
    CreateVersion(zentao_ref_url, sid, post_data)

# 录入传入参数
if __name__ == '__main__':
    main(sys.argv)

# python3 a.py  -z http://192.168.30.122/ -t 10  -j 10  -n Gateway-1.0.T.0   -p 33185 -f IMX6G2C -d 2021-12-6 -s "this is s " -u "liangyt"
# https://blog.csdn.net/fukainankai/article/details/101380268
# python3 a.py  -z http://192.168.30.122/ -t 3   -j 10  -n Gateway-1.0.1.21   -p 33185 -f IMX6G2C -d 2021-12-6 -s "this is new " -u "liangyt"
# python3 a.py  -z http://192.168.30.122/ -t 3   -j 10  -n Gateway-1.0.1.2   -p 33185 -f IMX6G2C -d 2021-12-6 -s "this is new " -u "liangyt